/*
 * @(#)MaintMtmDocumentRelationshipAction.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.dms.web;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.dcivision.audit.AuditTrailConstant;
import com.dcivision.audit.core.AuditTrailManager;
import com.dcivision.dms.DmsErrorConstant;
import com.dcivision.dms.DmsOperationConstant;
import com.dcivision.dms.bean.DmsDocument;
import com.dcivision.dms.bean.DmsDocumentDetail;
import com.dcivision.dms.bean.DmsRoot;
import com.dcivision.dms.bean.DmsValidation;
import com.dcivision.dms.bean.DmsVersion;
import com.dcivision.dms.bean.MtmDocumentRelationship;
import com.dcivision.dms.core.DocumentOperationManager;
import com.dcivision.dms.core.DocumentRetrievalManager;
import com.dcivision.dms.core.DocumentValidateManager;
import com.dcivision.dms.core.RootOperationManager;
import com.dcivision.dms.core.RootRetrievalManager;
import com.dcivision.dms.dao.DmsDocumentDAObject;
import com.dcivision.dms.dao.DmsRootDAObject;
import com.dcivision.dms.dao.MtmDocumentRelationshipDAObject;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.ErrorConstant;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.PermissionManager;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemParameterConstant;
import com.dcivision.framework.SystemParameterFactory;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.Utility;
import com.dcivision.framework.web.AbstractActionForm;
import com.dcivision.setup.web.AbstractMaintPermissionAction;


/**
  MaintUpdateAlertAction.java

  This class is for maint update alert action

    @author          Zoe Shum
    @company         DCIVision Limited
    @creation date   2/01/2004
    @version         $Revision: 1.63.2.4 $
*/

public class MaintMtmDocumentRelationshipAction extends AbstractMaintPermissionAction {

  public static final String REVISION = "$Revision: 1.63.2.4 $";

  protected String sListName = null;

  public MaintMtmDocumentRelationshipAction() {
    super();
    sListName =  "dmsRelationshipDocumentList";
  }

  /**
  * getMajorDAOClassName
  *
  * @return  The class name of the major DAObject will be used in this action.
  */
  
  public String getMajorDAOClassName() {
    return("com.dcivision.dms.dao.MtmDocumentRelationshipDAObject");
  }

  /**
  * getFunctionCode
  *
  * @return  The corresponding system function code of action.
  */
  
  public String getFunctionCode() {
		/*
		 * Update Code Start
		 * Author		Jim.Zhou
		 * Date			2006/05/11
		 * Bug			#5319
		 */
    return (this.functionCode);
	  /*
	   * Update Code End
	   */
  }

  /**
   * Method execute() - set request attributes and call super method
   * 
   * @param mapping
   *          ActionMapping from struts
   * @param form
   *          ActionForm from struts
   * @param request
   *          HttpServletReuqest
   * @param respond
   *          HttpServletRespond
   * @return ActionForward Return the action forward object for struts
   * @throws ServletException
   *           Throws ServletException
   */
  
  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
      throws ServletException {
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);

    MaintMtmDocumentRelationshipForm maintDocRelationshipForm = (MaintMtmDocumentRelationshipForm) form;
    RootRetrievalManager rootRetrievalManager = new RootRetrievalManager(sessionContainer, conn);
    DmsDocument documentRoot = null;

    String relationshipType = "";
    relationshipType = request.getParameter("relationshipType");

    String opMode = (maintDocRelationshipForm != null) ? maintDocRelationshipForm.getOpMode() : request.getParameter("opMode"); // maintForm.getOpMode();
    String navMode = (maintDocRelationshipForm != null) ? maintDocRelationshipForm.getNavMode() : request.getParameter("navMode"); // maintForm.getNavMode();
    String directPage = maintDocRelationshipForm.getDirectPage();

    // Set function code if necessary.
    if (!Utility.isEmpty(maintDocRelationshipForm.getCurFunctionCode())) {
      this.setFunctionCode(maintDocRelationshipForm.getCurFunctionCode());
    }

    ActionForward forward = this.retrieveFunctionCode(request, response, mapping);
    if (forward != null) {
      return forward;
    }

    // handle the new document relationship that are shortcut
    if (DmsDocument.DOCUMENT_LINK.equals(relationshipType)) {
      try {
        if (!GlobalConstant.OP_MODE_MY_FAVORITE.equals(maintDocRelationshipForm.getIsMyFavorite())) {

          // Retieve the root folder document object.
          documentRoot = docRetrievalManager.getRootFolderByRootID(TextUtility.parseIntegerObj(maintDocRelationshipForm.getRootID()));
          request.setAttribute("rootFolder", documentRoot);

          // Retrieve the folder list for folder tree listing.
          List folderTreeList = docRetrievalManager.getFolderByParentIDRootID(documentRoot.getID(), new Integer(maintDocRelationshipForm
              .getRootID()));
          request.setAttribute("folderTreeList", folderTreeList);

          // Retrieve the location path of the folder.
          Integer parentID = new Integer(maintDocRelationshipForm.getParentID());
          String path = docRetrievalManager.getLocationPath(parentID);
          request.setAttribute("location", path);

          // Retrieve the accessible public root list.
          List publicRootList = new ArrayList();
          if (!Utility.isEmpty(maintDocRelationshipForm.getDocumentID())) {
            DmsDocument docForRootList = docRetrievalManager.getDocumentByID(TextUtility.parseIntegerObj(maintDocRelationshipForm
                .getDocumentID()));
            DmsRoot rootForRootList = rootRetrievalManager.getRootObject(docForRootList.getRootID());
            if (DmsRoot.PERSONAL_ROOT.equals(rootForRootList.getRootType())) {
              publicRootList = rootRetrievalManager.getAccessiblePersonalRootsList();
            } else {
              publicRootList = rootRetrievalManager.getAllAccessibleRootsList();
            }

          }
          // List publicRootList =
          // rootRetrievalManager.getAllAccessibleRootsList();
          request.setAttribute("publicRootList", publicRootList);

        } else {
          DmsDocument doc = docRetrievalManager.getMyFavoriteObject();
          this.commit(request);

          // Retieve the root folder document object.
          documentRoot = docRetrievalManager.getRootFolderByRootID(doc.getRootID());
          request.setAttribute("rootFolder", documentRoot);

          // Retrieve the folder list for folder tree listing.
          List folderTreeList = new ArrayList();
          folderTreeList.add(docRetrievalManager.getMyFavoriteObject());
          request.setAttribute("folderTreeList", folderTreeList);

          // Retrieve the location path of the folder.
          Integer parentID = new Integer(maintDocRelationshipForm.getParentID());
          String path = docRetrievalManager.getLocationPath(parentID);
          if (Utility.isEmpty(path)) {
            path = docRetrievalManager.getLocationPath(doc.getID());
          }
          request.setAttribute("location", path);

          // Retrieve the accessible public root list.
          List publicRootList = new ArrayList();
          if (!Utility.isEmpty(maintDocRelationshipForm.getDocumentID())) {
            DmsDocument docForRootList = docRetrievalManager.getDocumentByID(TextUtility.parseIntegerObj(maintDocRelationshipForm
                .getDocumentID()));
            DmsRoot rootForRootList = rootRetrievalManager.getRootObject(docForRootList.getRootID());
            if (DmsRoot.PERSONAL_ROOT.equals(rootForRootList.getRootType())) {
              publicRootList = rootRetrievalManager.getAccessiblePersonalRootsList();
            } else {
              publicRootList = rootRetrievalManager.getAllAccessibleRootsList();
            }

          }
          // List publicRootList =
          // rootRetrievalManager.getAllAccessibleRootsList();
          request.setAttribute("publicRootList", publicRootList);

        }
      } catch (ApplicationException appEx) {
        this.rollback(request);
        handleApplicationException(request, appEx);
      }

      sessionContainer = null;
      conn = null;
      docRetrievalManager.release();
      rootRetrievalManager.release();

      if (!Utility.isEmpty(opMode)) {
        if (GlobalConstant.OP_MODE_INSERT.equals(opMode)) {
          // Insert operation.
          try {
            this.insertRecord(mapping, maintDocRelationshipForm, request, response);
            this.handleWorkflowRoutine(mapping, maintDocRelationshipForm, request, response, opMode, navMode);
            this.commit(request);
            addMessage(request, MESSAGE_RECORD_INSERT);
          } catch (ApplicationException appEx) {
            this.rollback(request);
            /* if SYS_CHARACTER_ERROR ,show the error message*/
            if (ErrorConstant.SYS_CHARACTER_ERROR.equals(appEx.getMsgCode())) {
              String sysInvalidCharacters = SystemParameterFactory.getSystemParameter(SystemParameterConstant.INVALID_CHARACTER);
              this.addError(request, appEx.getMsgCode(), sysInvalidCharacters);
            } else {
              this.addError(request, appEx.getMsgCode());
            }
          }
          if (isError(request)) {
            maintDocRelationshipForm.setNavMode(GlobalConstant.NAV_MODE_NEW);
            return mapping.findForward(GlobalConstant.NAV_MODE_NEW);
          } else {
            maintDocRelationshipForm.setNavMode(GlobalConstant.NAV_MODE_VIEW);
            return mapping.findForward(GlobalConstant.NAV_MODE_VIEW);
          }
        }
      } else if (!Utility.isEmpty(request.getParameter("documentID")) && !"null".equals(request.getParameter("documentID")) && "true".equals(request.getParameter("bFromContextMenu")) && !GlobalConstant.OP_MODE_MY_FAVORITE.equals(maintDocRelationshipForm.getIsMyFavorite())){
        this.init(mapping, maintDocRelationshipForm, request, response);
        maintDocRelationshipForm.setNavMode(GlobalConstant.NAV_MODE_NEW);
        request.setAttribute(GlobalConstant.ACTION_MODE, "N");
        return mapping.findForward("NP");
      }
      return (super.execute(mapping, form, request, response));

    } else {

      // Add By Jim Zhou 2007/0110 EIP-1292
      // MaintDmsDocumentForm documentForm = (MaintDmsDocumentForm) form;
      Integer documentIDs = TextUtility.parseIntegerObj(maintDocRelationshipForm.getDocumentID() == null ? request
          .getParameter("documentID") == null ? "" : (String) request.getParameter("documentID") : (String) maintDocRelationshipForm
          .getDocumentID());
      DmsDocument document = docRetrievalManager.getDocument(documentIDs);
      DocumentValidateManager docValidateManager = new DocumentValidateManager(sessionContainer, conn);
      StringBuffer message = new StringBuffer();

      DmsValidation validation = docValidateManager.validateOperateAction(document, false, "H");
      List lstIdMisRight = validation.getLstIdReject();
      List lstIdBeLocked = validation.getLstIdlocked();
      List lstIdBeDeleted = validation.getLstIdDeleted();
      List lstIdBeArchived = validation.getLstIdArchived();
      List lstIdRelationship = validation.getLstIdHaveRelationship();
      if (!lstIdMisRight.isEmpty() || !lstIdBeDeleted.isEmpty() || !lstIdBeArchived.isEmpty()) {
        for (int i = 0; i < lstIdMisRight.size(); i++) {
          this.addError(request, "errors.dms.no_permission", docRetrievalManager.getLocationPath((Integer) lstIdMisRight.get(i)));
        }
        for (int i = 0; i < lstIdBeLocked.size(); i++) {
          this.addError(request, "errors.dms.been_checkout", docRetrievalManager.getLocationPath((Integer) lstIdBeLocked.get(i)));
        }
        for (int i = 0; i < lstIdBeDeleted.size(); i++) {
          this.addError(request, "errors.dms.been_deleted", docRetrievalManager.getLocationPath((Integer) lstIdBeDeleted.get(i)));
        }
        for (int i = 0; i < lstIdBeArchived.size(); i++) {
          this.addError(request, "errors.dms.been_archived", docRetrievalManager.getLocationPath((Integer) lstIdBeArchived.get(i)));
        }
        if (Utility.isEmpty(maintDocRelationshipForm.getReturnTo())) {
          return mapping.findForward("Home");
        } else {
          ActionForward actionForward = new ActionForward();
          actionForward.setPath("/dms/" + maintDocRelationshipForm.getReturnTo());
          return actionForward;
        }
      }
      // Add End

      // handle the new document relationship that not are shortcut

      String tmpDocumentID = maintDocRelationshipForm.getDocumentID() == null ? request.getParameter("documentID") == null ? ""
          : (String) request.getParameter("documentID") : (String) maintDocRelationshipForm.getDocumentID();
      this.selectRelationshipList(TextUtility.parseIntegerObj(tmpDocumentID), request);
      this.selectIndirectRelationshipList(TextUtility.parseIntegerObj(tmpDocumentID), request);
      DocumentValidateManager validateManager = new DocumentValidateManager(sessionContainer, conn);

      // forward to the page create document relaltionship
      if (Utility.isEmpty(opMode)) {
        maintDocRelationshipForm.setNavMode(GlobalConstant.NAV_MODE_NEW);
        return mapping.findForward(DmsOperationConstant.CREATE_NEW_RELATION);
      } else if (GlobalConstant.OP_MODE_INSERT.equals(opMode)) {

        if (!Utility.isEmpty(request.getParameter("dummy_display_objectName"))) {
          try {
            // check duplicate file

            if (validateManager.checkDuplicateRelation(TextUtility.parseIntegerObj(maintDocRelationshipForm.getDocumentID()), TextUtility
                .parseIntegerObj(maintDocRelationshipForm.getRelatedDocumentID()), maintDocRelationshipForm.getRelationshipType())) {

              this.insertRecord(mapping, maintDocRelationshipForm, request, response);

              this.commit(request);
            }
            // add for showing the list
            this.selectRelationshipList(TextUtility.parseIntegerObj(tmpDocumentID), request);
            this.selectIndirectRelationshipList(TextUtility.parseIntegerObj(tmpDocumentID), request);

            String documentID = maintDocRelationshipForm.getDocumentID();
            String rootID = maintDocRelationshipForm.getRootID();
            String parentID = maintDocRelationshipForm.getParentID();

            form.reset(mapping, request);
            // set back the docid, rootid, parent id for reloading the document
            // info
            maintDocRelationshipForm.setDocumentID(documentID);
            maintDocRelationshipForm.setRootID(rootID);
            maintDocRelationshipForm.setParentID(parentID);

            this.init(mapping, maintDocRelationshipForm, request, response);
            addMessage(request, MESSAGE_RECORD_INSERT);
          } catch (ApplicationException appEx) {
            this.rollback(request);
            handleApplicationException(request, appEx);
          }
          if (isError(request)) {
            maintDocRelationshipForm.setNavMode(GlobalConstant.NAV_MODE_NEW);
            return mapping.findForward(DmsOperationConstant.CREATE_NEW_RELATION);
          } else {
            maintDocRelationshipForm.setNavMode(GlobalConstant.NAV_MODE_NEW);
            return mapping.findForward(DmsOperationConstant.CREATE_NEW_RELATION);
          }
        } else {
          maintDocRelationshipForm.setNavMode(GlobalConstant.NAV_MODE_NEW);
          return mapping.findForward(DmsOperationConstant.CREATE_NEW_RELATION);
        }

      } else if (GlobalConstant.OP_MODE_LIST_DELETE.equals(opMode)) {

        try {

          deleteListData(mapping, form, request, response);
          this.commit(request);

          addMessage(request, MESSAGE_RECORD_DELETE);

          // add for showing the list
          this.selectRelationshipList(TextUtility.parseIntegerObj(tmpDocumentID), request);
          this.selectIndirectRelationshipList(TextUtility.parseIntegerObj(tmpDocumentID), request);

          String documentID = maintDocRelationshipForm.getDocumentID();
          String rootID = maintDocRelationshipForm.getRootID();
          String parentID = maintDocRelationshipForm.getParentID();

          form.reset(mapping, request);
          // set back the docid, rootid, parent id for reloading the document
          // info
          maintDocRelationshipForm.setDocumentID(documentID);
          maintDocRelationshipForm.setRootID(rootID);
          maintDocRelationshipForm.setParentID(parentID);

        } catch (ApplicationException appEx) {
          this.rollback(request);
          handleApplicationException(request, appEx);
        }
        if (isError(request)) {
          maintDocRelationshipForm.setNavMode(GlobalConstant.NAV_MODE_NEW);
          return mapping.findForward(DmsOperationConstant.CREATE_NEW_RELATION);
        } else {
          maintDocRelationshipForm.setNavMode(GlobalConstant.NAV_MODE_NEW);
          return mapping.findForward(DmsOperationConstant.CREATE_NEW_RELATION);
        }

      }

      ActionForward tmpActionForward = null;
      return tmpActionForward;
    }
  }


   
  public void insertRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response)
      throws ApplicationException {
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    DocumentOperationManager docOperationManager = new DocumentOperationManager(sessionContainer, conn);

    // IndexManager idxHandler = FullTextIndexFactory.getInstance();

    MaintMtmDocumentRelationshipForm maintDocRelationshipForm = (MaintMtmDocumentRelationshipForm) form;

    if (!GlobalConstant.OP_MODE_MY_FAVORITE.equals(maintDocRelationshipForm.getIsMyFavorite())) {
      // is rootID have permission to create new document
      if (!isPermission(mapping, form, request, response)) {
        throw new ApplicationException(ErrorConstant.DMS_MESSAGE_NO_SHORTCUT_PERMISSION);
      }

      // is short cut then don't allow to short cut
      if (!isShortCut(mapping, form, request, response)) {
        throw new ApplicationException(ErrorConstant.DMS_MESSAGE_IS_ALREADY_SHORTCUT);
      }
    }
    MtmDocumentRelationship docRelationship = (MtmDocumentRelationship) maintDocRelationshipForm.getFormData();

    DmsDocument dmsDocument = new DmsDocument();
    DmsDocument sourceDocument = new DmsDocument();
    DmsDocument targetDocument = new DmsDocument();
    if (DmsDocument.DOCUMENT_LINK.equals(docRelationship.getRelationshipType())) {
      // Get new dmsDocument object to create instant
      if (docRelationship.getDocumentID() == null) {
        Integer tmpDocID = TextUtility.parseIntegerObj(request.getParameter("dummy_display_objectID"));
        docRelationship.setDocumentID(tmpDocID);
      }
      /*
       * Integer dummyRootID =docRelationship.getRootID(); Integer dummyParentID
       * =docRelationship.getParentID(); if
       * (request.getParameter("dummy_root_ID")!=null &&
       * request.getParameter("dummy_parent_ID")!=null) { dummyRootID =
       * TextUtility.parseIntegerObj(request.getParameter("dummy_root_ID"));
       * dummyParentID =
       * TextUtility.parseIntegerObj(request.getParameter("dummy_parent_ID")); }
       */

      sourceDocument = docRetrievalManager.getDocument(docRelationship.getDocumentID());//
      targetDocument = docRetrievalManager.getDocument(docRelationship.getParentID());//
      // Add By Jim Zhou 2006/11/30 EIP-782
      if (DmsVersion.ARCHIVED_STATUS.equals(dmsDocument.getItemStatus())) {
        throw new ApplicationException(ErrorConstant.DMS_MESSAGE_ARCHIVE_NOT_SHORTCUT);
      }
      // Add End

      dmsDocument.setDocumentName(docRelationship.getDocumentName());
      dmsDocument.setRootID(docRelationship.getRootID());
      dmsDocument.setParentID(docRelationship.getParentID());
      dmsDocument.setDocumentType(DmsDocument.DOCUMENT_LINK); // doc type is
                                                              // shortcut
                                                              // linkage
      dmsDocument.setItemStatus(GlobalConstant.STATUS_INACTIVE);
      dmsDocument.setCreateType(DmsOperationConstant.DMS_CREATE_BY_SYSTEM);//
      dmsDocument.setRecordStatus(GlobalConstant.RECORD_STATUS_ACTIVE);//
      dmsDocument.setItemSize(null);
      dmsDocument.setDescription(maintDocRelationshipForm.getDescription());

      List docDetailList = dmsDocument.getDocumentDetails();
      if (Utility.isEmpty(docDetailList)) {
        docDetailList = docRetrievalManager.getDocumentDetailList(dmsDocument.getID());
        dmsDocument.setDocumentDetails(docDetailList);

        if (!Utility.isEmpty(docDetailList)) {
          dmsDocument.setUserDefinedFieldID(((DmsDocumentDetail) docDetailList.get(0)).getUserDefinedFieldID());
        }
      }

      // dmsDocument = docOperationManager.createDocument(dmsDocument, null,
      // false);
      
      if ("0".equals(sourceDocument.getParentID().toString())){
        throw new ApplicationException(DmsErrorConstant.DMS_MESSAGE_UNABLE_SHORTCUT_ROOT_FOLDER);
      }
      
      dmsDocument = docOperationManager.createNewShortcut(sourceDocument, targetDocument, dmsDocument);//

      /* add the index in creating the document */

      // idxHandler.insertDocument(DmsIndexConverter.getIndexDocument(dmsDocument,
      // null));
      // docOperationManager.indexDocument(dmsDocument,GlobalConstant.OP_MODE_INSERT);
      // //lee comment:creteDocument method has do the index
    } else /*
             * if(DmsDocument.DOCUMENT_ANNOTATED_VERSION.equals(docRelationship.getRelationshipType()) ||
             * DmsDocument.DOCUMENT_EXTRACTED_SUMMARY.equals(docRelationship.getRelationshipType()) ||
             * DmsDocument.DOCUMENT_IN_OUT.equals(docRelationship.getRelationshipType()) )
             */{
      // add the relationship that are not short cut
      Integer tmpDocID = TextUtility.parseIntegerObj(request.getParameter("dummy_display_objectID"));

      // Integer tmpDocID =
      // TextUtility.parseIntegerObj(maintDocRelationshipForm.getRelatedDocumentID());
      dmsDocument = docRetrievalManager.getDocument(tmpDocID);
      // idxHandler.insertDocument(DmsIndexConverter.getIndexDocument(dmsDocument,
      // null));

    }

    // create new mtmdocumentRelationship
    docRelationship = docOperationManager.createDocumentRelationship(docRelationship, dmsDocument);

    /*
     * // log down in audit trail AuditTrailManager auditManager = new
     * AuditTrailManager(sessionContainer, conn); if
     * (sessionContainer.getUserRecordID() != null) {
     * auditManager.auditTrail(GlobalConstant.OBJECT_TYPE_DOCUMENT, dmsDocument,
     * AuditTrailConstant.ACCESS_TYPE_CREATE_SHORTCUT,
     * dmsDocument.getVersionNumber()); } auditManager.release();
     */
    maintDocRelationshipForm.setRelatedDocumentID(TextUtility.formatIntegerObj(dmsDocument.getID()));
    maintDocRelationshipForm.setFormData(docRelationship);
    form.setID(TextUtility.formatIntegerObj(dmsDocument.getID()));

    sessionContainer = null;
    conn = null;
    docRetrievalManager.release();
    docOperationManager.release();
    maintDocRelationshipForm.setObjectID(TextUtility.formatIntegerObj(dmsDocument.getID()));

    // insert permission data
    if ("TRUE".equals(maintDocRelationshipForm.getSetPermission())) {
      this.updateInheritanceFlag(mapping, form, request, response);
      this.updatePermissionObjects(mapping, form, request, response);
    }
  }
   
   
  public void init(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
     super.init(mapping, form, request, response);
     MaintMtmDocumentRelationshipForm actionForm = (MaintMtmDocumentRelationshipForm) form;    
     if(!Utility.isEmpty(actionForm.getObjectType())){
       com.dcivision.user.dao.UserPermissionInheritDAObject userPermInheritDAO = new com.dcivision.user.dao.UserPermissionInheritDAObject(this.getSessionContainer(request), this.getConnection(request));
       com.dcivision.user.bean.UserPermissionInherit tmpUserPermissionInherit = (com.dcivision.user.bean.UserPermissionInherit)userPermInheritDAO.getObjectByObjectTypeObjectID(actionForm.getObjectType(), new Integer(actionForm.getObjectID()));
       if (tmpUserPermissionInherit == null) {
         if(!SystemParameterFactory.getSystemParameterBoolean(SystemParameterConstant.DMS_NOT_INHERIT_FROM_PARENT)){
           actionForm.setInheritanceFlag(GlobalConstant.TRUE);
         } else{
           actionForm.setInheritanceFlag(null);  
         }        
       } else {
         actionForm.setInheritanceFlag(null);
       }
     }else{
       if(!SystemParameterFactory.getSystemParameterBoolean(SystemParameterConstant.DMS_NOT_INHERIT_FROM_PARENT)){
         actionForm.setInheritanceFlag(GlobalConstant.TRUE);
       } else{
         actionForm.setInheritanceFlag(null);  
       }   
     }
   }   

   
  public void selectRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
     SessionContainer sessionContainer = this.getSessionContainer(request);
     Connection conn = this.getConnection(request);

     MaintMtmDocumentRelationshipForm maintDocRelationshipForm = (MaintMtmDocumentRelationshipForm)form;
     DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
     MtmDocumentRelationshipDAObject docRelationshipDAO = new MtmDocumentRelationshipDAObject(sessionContainer, conn);


     MtmDocumentRelationship docRelationship =  (MtmDocumentRelationship)maintDocRelationshipForm.getFormData();
     if (DmsDocument.DOCUMENT_LINK.equals(docRelationship.getRelationshipType())) {
       DmsDocument relatedDoc = docRetrievalManager.getDocument(TextUtility.parseIntegerObj(maintDocRelationshipForm.getRelatedDocumentID()));
       //Get new dmsDocument object to create instant
        if (relatedDoc != null){
/*
          DmsDocument targetDocRoot = (DmsDocument)docRetrievalManager.getRootFolderByRootID(relatedDoc.getRootID());
          //String targetDocPermission = (String)permissionManager.getPermission(GlobalConstant.OBJECT_TYPE_DOCUMENT, targetDocRoot.getID());
log.debug("selecting link 3");
          relatedDoc = (DmsDocument) docRetrievalManager.getDocument(docRelationship.getDocumentID()); ;
          docRelationship.setDocumentName(relatedDoc.getDocumentName());
*/
        }


     }

     maintDocRelationshipForm.setFormData(docRelationship);
     sessionContainer = null;
     conn=null;
     docRetrievalManager.release();

   }

   
  public void updateRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
     SessionContainer sessionContainer = this.getSessionContainer(request);
     Connection conn = this.getConnection(request);
     DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
     DocumentOperationManager docOperationManager = new DocumentOperationManager(sessionContainer, conn);
     
     //is rootID have permission to create new document
     if (!isPermission(mapping,form,request,response)) {
      throw new ApplicationException(ErrorConstant.DMS_MESSAGE_NO_SHORTCUT_PERMISSION);
    } 
     
     //is short cut then don't allow to short cut
     if(!isShortCut(mapping,form,request,response)){
     	throw new ApplicationException(ErrorConstant.DMS_MESSAGE_IS_ALREADY_SHORTCUT);
     }

     MaintMtmDocumentRelationshipForm maintDocRelationshipForm = (MaintMtmDocumentRelationshipForm)form;
     MtmDocumentRelationship docRelationship = (MtmDocumentRelationship) maintDocRelationshipForm.getFormData();
     docRelationship.setRecordStatus(GlobalConstant.RECORD_STATUS_ACTIVE);
     DmsDocument dmsDocument = new DmsDocument();
     if (DmsDocument.DOCUMENT_LINK.equals(docRelationship.getRelationshipType())) {
       //Get new dmsDocument object to create instant
       if (docRelationship.getDocumentID() == null){
         Integer tmpDocID = TextUtility.parseIntegerObj(request.getParameter("dummy_display_objectID"));
         docRelationship.setDocumentID(tmpDocID);
       }

       dmsDocument = docRetrievalManager.getDocument(docRelationship.getRelatedDocumentID()); ;
       dmsDocument.setDocumentName(docRelationship.getDocumentName());
       dmsDocument.setParentID(docRelationship.getParentID());
       dmsDocument.setRootID(docRelationship.getRootID());
       dmsDocument.setDocumentType(DmsDocument.DOCUMENT_LINK); //doc type is shortcut linkage
       dmsDocument.setItemStatus(GlobalConstant.STATUS_INACTIVE);
       dmsDocument.setItemSize(null);
       dmsDocument.setDescription(maintDocRelationshipForm.getDescription());
       dmsDocument = docOperationManager.updateDocument(dmsDocument);
     }

     //create new mtmdocumentRelationship
     MtmDocumentRelationshipDAObject dmsMtmDocumentRelationshipDAO = new MtmDocumentRelationshipDAObject (sessionContainer, conn);
     docRelationship = (MtmDocumentRelationship)dmsMtmDocumentRelationshipDAO.getObjectByRelatedDocID(docRelationship.getRelatedDocumentID(),docRelationship.getRelationshipType());
     docRelationship = docOperationManager.updateDocumentRelationship(docRelationship, dmsDocument);
     // log down in audit trail
     AuditTrailManager auditManager = new AuditTrailManager(sessionContainer, conn);
     if (sessionContainer.getUserRecordID() != null) {
       auditManager.auditTrail(GlobalConstant.OBJECT_TYPE_DOCUMENT, dmsDocument, AuditTrailConstant.ACCESS_TYPE_UPDATE, dmsDocument.getVersionNumber());
     }
     auditManager.release();
     maintDocRelationshipForm.setRelatedDocumentID(TextUtility.formatIntegerObj(dmsDocument.getID()));
     maintDocRelationshipForm.setFormData(docRelationship);

     sessionContainer = null;
     conn=null;
     docRetrievalManager.release();
     docOperationManager.release();

   }

   
  public void deleteRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
     SessionContainer sessionContainer = this.getSessionContainer(request);
     Connection conn = this.getConnection(request);
     DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
     DocumentOperationManager docOperationManager = new DocumentOperationManager(sessionContainer, conn);

     MaintMtmDocumentRelationshipForm maintDocRelationshipForm = (MaintMtmDocumentRelationshipForm)form;
     MtmDocumentRelationship docRelationship = (MtmDocumentRelationship) maintDocRelationshipForm.getFormData();
     DmsDocument relatedDocument = new DmsDocument();
     if (DmsDocument.DOCUMENT_LINK.equals(docRelationship.getRelationshipType())) {
       relatedDocument = docRetrievalManager.getDocument(docRelationship.getRelatedDocumentID());
       docOperationManager.deleteDocument(relatedDocument);
     }


     //docOperationManager.deleteDocumentRelationship(docRelationship.getID(), relatedDocument);
     MtmDocumentRelationshipDAObject dmsMtmDocumentRelationshipDAO = new MtmDocumentRelationshipDAObject (sessionContainer, conn);
     docRelationship = (MtmDocumentRelationship)dmsMtmDocumentRelationshipDAO.getObjectByRelatedDocID(docRelationship.getRelatedDocumentID(),docRelationship.getRelationshipType());
//     Integer tempDocumentID = docRelationship.getDocumentID();
//     docRelationship.setDocumentID(docRelationship.getRelatedDocumentID());
//     docRelationship.setRelatedDocumentID(tempDocumentID);
//     docRelationship.setRecordStatus(GlobalConstant.RECORD_STATUS_INACTIVE);
//     docRelationship.setID(docRelationship.getID());
     
     dmsMtmDocumentRelationshipDAO.deleteObject(docRelationship);


     // log down in audit trail
     AuditTrailManager auditManager = new AuditTrailManager(sessionContainer, conn);
     if (sessionContainer.getUserRecordID() != null) {
       auditManager.auditTrail(GlobalConstant.OBJECT_TYPE_DOCUMENT, relatedDocument, AuditTrailConstant.ACCESS_TYPE_DELETE_SHORTCUT, relatedDocument.getVersionNumber());
     }
     auditManager.release();
     sessionContainer = null;
     conn=null;
     docRetrievalManager.release();
     docOperationManager.release();

   }

   public void deleteListData(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    MaintMtmDocumentRelationshipForm relationshipForm = (MaintMtmDocumentRelationshipForm)form;
    String[] idAry = request.getParameterValues("basicSelectedID");


    Connection conn = null;
      conn = this.getConnection(request);
      DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(this.getSessionContainer(request), conn);
      DocumentOperationManager docOperationManager = new DocumentOperationManager(this.getSessionContainer(request), conn);

      MaintMtmDocumentRelationshipForm maintDocRelationshipForm = (MaintMtmDocumentRelationshipForm)form;
      MtmDocumentRelationship docRelationship = (MtmDocumentRelationship) maintDocRelationshipForm.getFormData();

      DmsDocument relatedDocument = new DmsDocument();
      log.debug("delelete docRelationship document id:"+docRelationship.getID());

      if (!Utility.isEmpty(idAry)) {
        for (int i = 0; i < idAry.length; i++) {
          log.debug("select delete doc:"+idAry[i]);
          //log.debug("select delete doc name:"+relatedDocument.getDocumentName());
          //docOperationManager.deleteNonShortCutRelationship (docRelationship.getDocumentID(), TextUtility.parseIntegerObj(idAry[i]),"");
          docOperationManager.deleteRelationship(TextUtility.parseIntegerObj(idAry[i]));
          //docOperationManager.deleteDocumentRelationship(TextUtility.parseIntegerObj(idAry[i]), relatedDocument);
        }
      }


      docRetrievalManager.release();
      docOperationManager.release();
   }

  public void selectRelationshipList(Integer documentID,HttpServletRequest request){
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    //DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    MtmDocumentRelationshipDAObject dmsMtmDocumentRelationshipDAO = new MtmDocumentRelationshipDAObject (sessionContainer, conn);
    List relationDocumentList = null;

    try{
       relationDocumentList = dmsMtmDocumentRelationshipDAO.getListByIDRelationType(documentID,"");
    } catch (Exception ee) {
      log.error(ee, ee);
    }

   request.setAttribute(sListName,relationDocumentList);
  }
  
  public void selectIndirectRelationshipList(Integer documentID,HttpServletRequest request){
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    //DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    MtmDocumentRelationshipDAObject dmsMtmDocumentRelationshipDAO = new MtmDocumentRelationshipDAObject (sessionContainer, conn);
    List IndirectRelationDocumentList = null;

    try{
    	IndirectRelationDocumentList = dmsMtmDocumentRelationshipDAO.getListByRelationIDRelationType(documentID,"");
    } catch (Exception ee) {
      log.error(ee, ee);
    }

   request.setAttribute("IndirectRelationDocumentList",IndirectRelationDocumentList);
  }
  
  
  /**
   *  Method execute() - set request attributes and call super method
   *
   *  @param      mapping               ActionMapping from struts
   *  @param      form                  ActionForm from struts
   *  @param      request               HttpServletReuqest
   *  @param      respond               HttpServletRespond
   *  @return     ActionForward         Return the action forward object for struts
   *  @throws     ApplicationException  Throws ApplicationException
   */
  //the permission is cortrol the short cut folder
  public boolean isPermission(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException{
    boolean istrue = true;
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    MaintMtmDocumentRelationshipForm maintDocumentRelationshipForm = (MaintMtmDocumentRelationshipForm)form;
    Integer rootID = request.getParameter("rootID") == null ? TextUtility.parseIntegerObj(maintDocumentRelationshipForm.getRootID()) :
    TextUtility.parseIntegerObj(request.getParameter("rootID"));
    
    //DmsDocumentDAObject dmsDocumentDAObject = new DmsDocumentDAObject(sessionContainer,conn);    
    //DmsDocument documentRoot = (DmsDocument)dmsDocumentDAObject.getObjectByID(rootID);
    String parentID = maintDocumentRelationshipForm.getParentID();
    Integer parentId = TextUtility.parseIntegerObj(parentID);
        
    DmsRootDAObject dmsRootDAObject = new DmsRootDAObject(sessionContainer,conn);
    DmsRoot documentRoot = (DmsRoot)dmsRootDAObject.getObjectByID(rootID);
    
//    MtmDocumentRelationship docRelationship = (MtmDocumentRelationship) maintDocumentRelationshipForm.getFormData();
//    Integer targetDocID = docRelationship.getDocumentID();
//    DmsDocument targetDoc = (DmsDocument)dmsDocumentDAObject.getObjectByID(targetDocID);
//    String tempType =targetDoc.getDocumentType();
    
    PermissionManager permissionManager = sessionContainer.getPermissionManager();
    String functionCode =maintDocumentRelationshipForm.getCurFunctionCode();
    String sFunctionCode = null;
    sFunctionCode = sessionContainer.getAppContainer().getSysFunctionByFunctionID(new Integer(6001)).getFunctionCode();
    
    
    //if(DmsDocument.DOCUMENT_TYPE.equals(tempType)||DmsDocument.COMPOUND_DOC_TYPE.equals(tempType)){
      if (DmsOperationConstant.DMS_PERSONAL_ROOT.equals(documentRoot.getRootName())&&!"0".equals(parentID)) {      
        if (permissionManager.hasAccessRight(sFunctionCode, "I")) {
          istrue = true;
        }else{
          istrue = false;
        }
      } else {
        if(permissionManager.hasAccessRight(GlobalConstant.OBJECT_TYPE_DOCUMENT,parentId,"I")){
            istrue = true;
        }else{
            istrue = false;
        }    
      } 
//    }else{
//      if (DmsOperationConstant.DMS_PERSONAL_ROOT.equals(documentRoot.getRootName())) {      
//      	if (permissionManager.hasAccessRight(sFunctionCode, "F")) {
//          istrue = true;
//        }else{
//          istrue = false;
//        }
//      } else {
//        if(permissionManager.hasAccessRight(conn,"D",parentId,"F")){
//          istrue = true;
//        }else{
//          istrue = false;
//        }    
//      }     	
//    }
    return istrue;
  }
  
  //if the document or folder is short cut then dont'n allow to short cut
  public boolean isShortCut(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException{
    boolean istrue = true;
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    String relationshipType="";
    relationshipType = request.getParameter("relationshipType");
    
    MaintMtmDocumentRelationshipForm maintDocRelationshipForm = (MaintMtmDocumentRelationshipForm)form;
    MtmDocumentRelationship docRelationship = (MtmDocumentRelationship) maintDocRelationshipForm.getFormData();
    Integer documentID = docRelationship.getDocumentID();
    
    DmsDocumentDAObject dmsDocumentDAOjbect = new DmsDocumentDAObject(sessionContainer,conn);
    DmsDocument relatedDocument = (DmsDocument)dmsDocumentDAOjbect.getObjectByID(documentID);
    
    if (DmsDocument.DOCUMENT_LINK.equals(relatedDocument.getDocumentType())) {
      	istrue = false;
      }
    return istrue;
  } 
  
  public DmsDocument createMyFavoriteObject(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException{
    DmsDocument docDocument = new DmsDocument();
    String myFavoriteName = SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_MYFAVORITE_FOLDER_NAME);
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    MaintMtmDocumentRelationshipForm maintDocRelationshipForm = (MaintMtmDocumentRelationshipForm)form;
    
    boolean hasMyFavorite = false;
    
    DmsRootDAObject rootDAO = new DmsRootDAObject(sessionContainer, conn);
    DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionContainer, conn);
    
    try {      
      DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
      DocumentOperationManager docOperationManager = new DocumentOperationManager(sessionContainer, conn);
      RootOperationManager rootOperationManager = new RootOperationManager(sessionContainer, conn);
      MtmDocumentRelationship docRelationship = new MtmDocumentRelationship();
      
      Integer rootID = null;
      Integer parentID = null;
      DmsDocument dmsDocument = null;   
      
       //achieve current user's persoanl object
      Integer userID = sessionContainer.getUserRecordID();      
      List rootList = rootDAO.getRootByOwnerIDAndType(userID, DmsRoot.PERSONAL_ROOT, GlobalConstant.RECORD_STATUS_ACTIVE);
      DmsRoot dmsRoot =  (DmsRoot)rootList.get(0);

      DmsRoot rootPoint = null;
      if (rootList.size() == 0) {
        // Create default root for user without root point
        log.debug("no default root, going to create one");
        rootPoint = rootOperationManager.createDefaultPersonalRootPointForUser(userID);
        this.commit(request);
      }    
    
      DmsDocument documentRoot = docRetrievalManager.getRootFolderByRootID(dmsRoot.getID());
      rootID = documentRoot.getRootID();
      parentID = documentRoot.getID();      
      
      //check current personal's folder have myFavorite folder or not 
      List docList = dmsDocumentDAO.getListByParentID(parentID, rootID, DmsDocument.FOLDER_TYPE);
      for (int i=0 ;i<docList.size(); i++){
        dmsDocument = (DmsDocument)docList.get(i);
        if(myFavoriteName.trim().equals(dmsDocument.getDocumentName().trim())){
          rootID= dmsDocument.getRootID();
          parentID = dmsDocument.getID();
          hasMyFavorite = true;
          break;
        }
      } 
      
      if(!hasMyFavorite){
        DmsDocument docTemp = this.createMyFavoriteFolder(request,documentRoot);
        docDocument = docTemp;
      }else{
        docDocument = dmsDocument;
      }
      
      rootDAO = null;
      dmsDocumentDAO = null;
      return docDocument;
    }catch (Exception e) {
      log.error(e, e);
      this.rollback(request);
      throw new ApplicationException(ErrorConstant.COMMON_FATAL_ERROR, e);
    }
    
  }
  
  public DmsDocument createMyFavoriteFolder(HttpServletRequest request, DmsDocument documentRoot) throws ApplicationException{
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);    
    String myFavoriteName = SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_MYFAVORITE_FOLDER_NAME);
    DocumentOperationManager docOperationManager = new DocumentOperationManager(sessionContainer, conn);
    DmsDocument docDocument = new DmsDocument();
    
    docDocument.setDocumentName(myFavoriteName);
    docDocument.setDocumentType(DmsDocument.FOLDER_TYPE);
    docDocument.setParentID(documentRoot.getID());
    docDocument.setRootID(documentRoot.getRootID());
    docDocument.setPriority(GlobalConstant.PRIORITY_MEDIUM);
    docDocument.setCreateType(DmsOperationConstant.DMS_CREATE_BY_SYSTEM);
    docDocument.setEffectiveStartDate(Utility.getCurrentTimestamp());
    docDocument.setItemSize(new Integer(0));
    docDocument.setRecordStatus(GlobalConstant.STATUS_ACTIVE);
    docDocument.setItemStatus(DmsVersion.AVAILABLE_STATUS);  
        
    docDocument = docOperationManager.createFolder(docDocument);
    this.commit(request);
    return docDocument;
  }
 
  
  /**
   * updateInheritanceFlag
   *
   * @param mapping
   * @param form
   * @param request
   * @param response
   * @throws ApplicationException
   */
  public void updateInheritanceFlag(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    MaintMtmDocumentRelationshipForm  actionForm = (MaintMtmDocumentRelationshipForm)form;
    boolean inheritFlag = GlobalConstant.TRUE.equals(actionForm.getInheritanceFlag());

    com.dcivision.user.dao.UserPermissionInheritDAObject userPermInheritDAO = new com.dcivision.user.dao.UserPermissionInheritDAObject(this.getSessionContainer(request), this.getConnection(request));

    if (inheritFlag) {
      userPermInheritDAO.deleteObjectByObjectTypeObjectID(actionForm.getObjectType(), new Integer(actionForm.getObjectID()));
    } else {
      com.dcivision.user.bean.UserPermissionInherit tmpUserPermissionInherit = new com.dcivision.user.bean.UserPermissionInherit();
      tmpUserPermissionInherit.setObjectType(GlobalConstant.OBJECT_TYPE_DOCUMENT);
      tmpUserPermissionInherit.setObjectID(new Integer(actionForm.getObjectID()));
      tmpUserPermissionInherit.setInheritanceFlag(GlobalConstant.FALSE);
      tmpUserPermissionInherit.setRecordStatus(GlobalConstant.RECORD_STATUS_ACTIVE);
      userPermInheritDAO.updateObject(tmpUserPermissionInherit);
    }
  }
  
  /**
   * getObjectType
   *
   * @return  The corresponding object type of permission setup action.
   */
  
  public String getObjectType() {
    return(GlobalConstant.OBJECT_TYPE_DOCUMENT);
  }  
    
}
